package com.study.zouchao.superproject.comtaskdetail;

import android.content.Context;
import android.hardware.usb.UsbRequest;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import com.study.zouchao.superproject.R;
import com.study.zouchao.superproject.comtaskdetail.adapter.SupportListAdapter;
import com.study.zouchao.superproject.comtaskdetail.model.EnrollResult;
import com.study.zouchao.superproject.comtaskdetail.model.TaskDetailModel;
import com.study.zouchao.superproject.comtaskdetail.model.TaskDetailResult;
import com.study.zouchao.superproject.login.model.entity.User;
import com.study.zouchao.superproject.logininterceptor.LoginStatusUtil;
import com.study.zouchao.superproject.travellist.adapter.TravelRecyclerViewAdapter;
import com.study.zouchao.superproject.util.App;
import com.study.zouchao.superproject.util.LogLongUtil;
import com.study.zouchao.superproject.util.StringUtils;
import com.study.zouchao.superproject.util.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Subscription;
import rx.functions.Action1;

/**
 * Created by Administrator on 2017/6/20.
 */

public class TaskDetailPresenter implements ITaskDetailContract.ITaskDetailPresenter {
    //private List<TravelItem> mData;
    private List<TaskDetailResult.TaskDetailDataBean.EnrolledListBean> mData;
    private Context mContext;
    private ITaskDetailContract.ITaskDetailView mView;
    private SupportListAdapter mAdapter;
    private TaskDetailModel mConnModel;

    private int mTaskId = 20;
    private Subscription mSupConn, mSubIsEnrolled, mSubEnrolledNow;

    //正在加载数据
    private boolean mIsLoadingData = false;

    //用户操作：下拉刷新
    private static final String ACTION_REFRESHING = "ACTION_REFRESHING";
    //用户操作：上滑更多
    private static final String ACTION_SEE_MORE = "ACTION_SEE_MORE";

    public TaskDetailPresenter(Context context, ITaskDetailContract.ITaskDetailView view) {
        mContext = context;
        mView = view;
        mConnModel = new TaskDetailModel();
        init();
    }

    public TaskDetailPresenter(Context context, ITaskDetailContract.ITaskDetailView view, int taskId) {
        mContext = context;
        mView = view;
        mTaskId = taskId;
        mConnModel = new TaskDetailModel();
        init();
    }

    private void init() {
        mData = new ArrayList<>();
    }

    @Override
    public void onRefreshingData() {
        conn(ACTION_REFRESHING);
    }

    private void conn(final String action) {
        if (!isValidUserAction(action)) {
            Toast.makeText(mContext, "用户操作有误", Toast.LENGTH_SHORT).show();
            return;
        }
        Log.i("请求的taskId", mTaskId+"");
        Map<String, String> requestParams = getRequestParams(action);
        if (requestParams==null || requestParams.isEmpty()) return;
        toggleLoading(action, true);
        mIsLoadingData = true;
        mSupConn = mConnModel.connTaskDetail(requestParams)
                .subscribe(new Action1<TaskDetailResult>() {
                    @Override
                    public void call(TaskDetailResult travelListResult) {
                        judgeGetResult(travelListResult, action);
                        toggleLoading(action, false);
                        mIsLoadingData = false;
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        failGetList(throwable, action);
                        toggleLoading(action, false);
                        mIsLoadingData = false;
                        loadFailAndFinishCurrentActivity(throwable.getMessage());
                    }
                });
    }


    private void judgeGetResult(TaskDetailResult result, String action) {
        switch (result.getCode()) {
            case 21301 :
                successGetList(result, action);
                LogLongUtil.logI("任务详情", result.toString());
                //TODO:连接isEnrolled
//                ToastUtils.showShort(mContext, "任务详情获取成功");
                break;
            default:
//                ToastUtils.showShort(mContext, "任务详情获取失败");
                loadFailAndFinishCurrentActivity(result.getMessage());
                break;
        }
    }

    private void loadFailAndFinishCurrentActivity(String msg) {
        ToastUtils.showShort(App.getAppContext(), "任务详情获取失败、"+msg);
        mView.finishCurrentActivity();
    }

    private void successGetList(TaskDetailResult result, String action) {
        if (action.equals(ACTION_REFRESHING)) {
            mData.clear();
        }
        List<TaskDetailResult.TaskDetailDataBean.EnrolledListBean> newData = result.getData().getEnrolledList();
        mData.addAll(newData);
        mAdapter.notifyDataSetChanged();
        //显示界面数据
        mView.loadInfos(result.getData());
    }

    private void failGetList(Throwable throwable, String action) {
        throwable.printStackTrace();
        ToastUtils.showLong(mContext, throwable.getMessage());
    }

    private void toggleLoading(String userAction, boolean isShow) {
        if (userAction.equals(ACTION_REFRESHING))   mView.showRefreshingLoading(isShow);
    }

    private Map<String, String> getRequestParams(String action) {
        Map<String, String> params = new HashMap<>();
        params.put("taskId", mTaskId+"");
        return params;
    }

    private boolean isValidUserAction(String action) {
        return (action!=null) && (action.equals(ACTION_REFRESHING) || action.equals(ACTION_SEE_MORE));
    }


    @Override
    public void initRecyclerView(RecyclerView rv) {
        rv.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        mData = new ArrayList<>();
        //为RecyclerView加Adapter
        mAdapter = new SupportListAdapter(mContext, mData);
        //添加上滑更多监听器
        rv.setAdapter(mAdapter);
        //请求数据
        conn(ACTION_REFRESHING);
    }

    @Override
    public void connEnroll() {
        Map<String, String> reqParams = getEnrollReqParams();
        if (reqParams==null) return;
        mView.showLoading(true);
        mSubEnrolledNow = mConnModel.connEnrollNow(reqParams)
                .subscribe(new Action1<EnrollResult>() {
                    @Override
                    public void call(EnrollResult enrollResult) {
                        judgeEnrollResult(enrollResult);
                        mView.showLoading(false);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        onFailureEnroll(throwable);
                        mView.showLoading(false);
                        mView.showSnackBar(throwable.getMessage(), Snackbar.LENGTH_SHORT);
                    }
                });
    }

    private void judgeEnrollResult(EnrollResult enrollResult) {
        switch (enrollResult.getCode()) {
            case 28003 :
                successEnroll(enrollResult);
                mView.showSnackBar(enrollResult.getMessage(), Snackbar.LENGTH_LONG);
                break;
            default:
                mView.showSnackBar(enrollResult.getMessage(), Snackbar.LENGTH_SHORT);
                break;
        }
    }

    private void successEnroll(EnrollResult enrollResult) {
        LogLongUtil.logD("申请成功", enrollResult.toString());
        conn(ACTION_REFRESHING);
    }

    private void onFailureEnroll(Throwable throwable) {
        mView.showSnackBar(throwable.getMessage(), Snackbar.LENGTH_SHORT);
    }

    private HashMap<String, String> getEnrollReqParams() {
        User userBean = LoginStatusUtil.getLoginDataByBean(mContext);
        if (userBean==null || StringUtils.isEmpty(userBean.getUserName())) {
            return null;
        }
        HashMap<String, String> params = new HashMap<>();
        params.put("taskId", mTaskId+"");
        params.put("userName", userBean.getUserName());
        return params;
    }

    @Override
    public void onDestroyPresente() {
        //取消登陆任务
        if ( mSupConn != null && !mSupConn.isUnsubscribed()) {
            mSupConn.unsubscribe();
        }
        if ( mSubIsEnrolled != null && !mSubIsEnrolled.isUnsubscribed()) {
            mSubIsEnrolled.unsubscribe();
        }
        if ( mSubEnrolledNow != null && !mSubEnrolledNow.isUnsubscribed()) {
            mSubEnrolledNow.unsubscribe();
        }
    }
}
